package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
	"unicode"
	"unicode/utf8"
)

func main() {
	//a := 10
	//var i *int = &a
	var i *int = new(int) //只定义一个指针,不new时,此时指针是nil不能给指针赋值,new的话指针为0,可以给指针赋值
	*i = 11
	fmt.Printf("%p----%d\n", i, *i)

	//创建空的map
	test1 := map[string]int{}
	test1["bob"] = 10
	fmt.Println(test1)

	//向一个nil值的map存入元素将导致一个panic异常，除了var i  map[string]int,这种定义其他都是可以赋值的
	ages := make(map[string]int) // mapping from strings to ints
	fmt.Println(ages == nil)     // "false",make同new,给数据结构赋值了初始值,此时数据结构为空，不等于nil
	ages["Hua"] = 25
	ages["Tom"] = 29
	ages["Jack"] = 32
	ages["bob"] = ages["bob"] + 1 // ages["bob"]失败时将返回0
	ages["bob"]++
	fmt.Println(ages, ages["Hua"])
	ages["Hua"] = 26
	delete(ages, "Jack")
	fmt.Println(ages)
	//一个变量就是存储k，两个变量就是k、v
	for i := range ages {
		fmt.Println(i)
	}
	//可以使用sort包的Strings函数对字符串slice进行排序,进而实现对map的排序
	names := make([]string, 0, len(ages))
	for name := range ages {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		fmt.Println(name, ages[name])
	}
	age, ok := ages["amy"]
	fmt.Println(age, ok, ages["amy"], ages)

	fmt.Println(equal(test1, ages))
	str := "a A"
	fmt.Printf("%q\n", str)

	var graph = make(map[string]map[string]bool)
	edges := graph["hello"]
	fmt.Println(edges, edges == nil, graph == nil) //make创建map时，map!=nil,但是map中的值不存在时依然是nil
	//dump()
	dump2()

}

func equal(x, y map[string]int) bool {
	if len(x) != len(y) {
		return false
	}
	for k, xv := range x {
		if yv, ok := y[k]; !ok || yv != xv {
			return false
		}
	}
	return true
}

// func dump() {
// 	seen := make(map[string]bool) // a set of strings
// 	input := bufio.NewScanner(os.Stdin)
// 	for input.Scan() {
// 		line := input.Text()
// 		if !seen[line] {
// 			seen[line] = true
// 			fmt.Println(line)
// 		}
// 	}
// 	if err := input.Err(); err != nil {
// 		fmt.Fprintf(os.Stderr, "dedup: %v\n", err)
// 		os.Exit(1)
// 	}
// }

func dump2() {
	counts := make(map[rune]int)    // counts of Unicode characters
	var utflen [utf8.UTFMax + 1]int // count of lengths of UTF-8 encodings,type:[5]int
	invalid := 0                    // count of invalid UTF-8 characters
	in := bufio.NewReader(os.Stdin)
	for {
		r, n, err := in.ReadRune() // returns rune, nbytes, error
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "charcount: %v\n", err)
			os.Exit(1)
		}
		if r == unicode.ReplacementChar && n == 1 {
			invalid++
			continue
		}
		counts[r]++
		utflen[n]++
	}
	fmt.Printf("rune\tcount\n")
	for c, n := range counts {
		fmt.Printf("%q\t%d\n", c, n)
	}
	fmt.Print("\nlen\tcount\n")
	for i, n := range utflen {
		if i > 0 {
			fmt.Printf("%d\t%d\n", i, n)
		}
	}
	if invalid > 0 {
		fmt.Printf("\n%d invalid UTF-8 characters\n", invalid)
	}
}
